package io.github.fb513.transport.command;

import com.fasterxml.jackson.databind.JsonNode;
import io.github.fb513.common.constant.RabbitConstants;
import io.github.fb513.common.model.BaseData;
import io.github.fb513.common.model.MessageInfo;
import io.github.fb513.transport.model.UserSession;
import io.github.fb513.transport.queue.MessageQueueSender;
import io.github.fb513.transport.util.JsonUtils;
import io.github.fb513.transport.util.SessionHolder;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 参考SpringMVC的HandlerMethodArgumentResolver设计的命令链
 */
@Slf4j
public class CommandChain {

    private final List<AbstractCommand> commandList;
    private final MessageQueueSender messageSender;

    public CommandChain(MessageQueueSender messageSender) {
        this(messageSender, new ArrayList<>());
    }

    public CommandChain(MessageQueueSender messageSender, List<AbstractCommand> commandList) {
        this.messageSender = messageSender;
        this.commandList = commandList;
    }

    public void add(AbstractCommand command) {
        if (commandList == null) {
            throw new IllegalStateException("command chain is null");
        }
        commandList.add(command);
    }

    public void execute(ChannelHandlerContext ctx, MessageInfo<JsonNode> msg) {
        boolean hasHandled = false;
        for (AbstractCommand command : commandList) {
            if (command.supportsCommand(msg.getHeader().getCommand())) {
                hasHandled = true;
                command.executeCommand(ctx, msg);
            }
        }
        if (!hasHandled) {
            log.info("-----sendMsg-----");
            UserSession session = SessionHolder.getSession(ctx);
            if (session == null) {
                return;
            }
            MessageInfo<BaseData<JsonNode>> respMessage = MessageInfo.getJsonMessage(msg.getHeader().getCommand(),
                    new BaseData<>(session.getUserInfo().getUserId(), session.getUserInfo().getClientType(), msg.getContent()));
            sendToMQAsync(JsonUtils.formatObjToJson(respMessage));
        }
    }

    public void sendToMQAsync(String msg) {
       messageSender.sendAsync(RabbitConstants.im_to_web_message, msg);
    }

}
